//
//  SQLitManager.swift
//  01-MyMFDB演练
//
//  Created by  NorthCity on 15/11/21.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
///数据库名称
private let dbName = "readme.db"
///数据库管理工具
class SQLitManager {
    static let sharedManager = SQLitManager()
    
    /// 全局数据库队列,支持线程操作
    var queue:FMDatabaseQueue
    
   private init(){
      var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
      path = (path as NSString).stringByAppendingPathComponent(dbName)
      print(path)
      queue = FMDatabaseQueue(path: path)
      createTable()
    }
/// 执行 sql 返回字典数组
    func execRecordSet(sql:String) -> [[String:AnyObject]]{
        var result = [[String:AnyObject]]()
        SQLitManager.sharedManager.queue.inDatabase { (db) -> Void in
            print(NSThread.currentThread())
            guard let rs = db.executeQuery(sql)else{
                print("查询失败")
                return
            }
            while rs.next(){
//                1 列数
                let colCount = rs.columnCount()
//                2 创建字典
                var dict = [String:AnyObject]()
//                3 遍历每一列
                for col in 0..<colCount{
                    let name = rs.columnNameForIndex(col)
                    let obj = rs.objectForColumnIndex(col)
                    dict[name] = obj
                }
                result.append(dict)
            }
            
        }
        return result
    }
    
/// 创建数据表
    private func createTable(){
       let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
       let sql = try!String(contentsOfFile: path)
        queue.inTransaction { (db,_) -> Void in
            if db.executeStatements(sql){
                print("创表成功")
            }else{
                print("创表失败")
            }
        }
        
    }
    
   }